package com.lagou.homework04;

import java.util.Date;

public class TicketThreadTest extends Thread{
    private int balance; // 描述车票数量
    private static Date d1 = new Date();
    public TicketThreadTest() {
    }

    public TicketThreadTest(int balance) {
        setBalance(balance);
    }

    public int getBalance() {
        return balance;
    }
    public void setBalance(int balance) {
            this.balance = balance;

    }

    @Override
    public  void run() {

        synchronized (d1) {//注意事项，需要d1成为唯一的一把锁，所以要提高到类层级
            int b1 = getBalance(); // 模拟从后台查询火车票余额
            if(b1 > 0 && b1 <= 100) {
                System.out.println("正在出票......");
                b1--;
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("请拿好票");
            } else {
                System.out.println("火车票的数量不合理！");
            }
            setBalance(b1);
        }
    }


    public static void main(String[] args) {

        TicketThreadTest ttt1 = new TicketThreadTest(100);
        ttt1.start();
        TicketThreadTest ttt2 = new TicketThreadTest(100);
        ttt2.start();
        TicketThreadTest ttt3 = new TicketThreadTest(100);
        ttt3.start();
        try {
            ttt1.join();
            ttt2.join();
            ttt3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("火车票剩余数量：" + ttt3.getBalance());

    }


}
